package com.jay.compass.adapter;

import java.util.ArrayList;
import java.util.LinkedList;

import com.jay.compass.R;
import com.jay.compass.R.drawable;
import com.jay.compass.R.id;
import com.jay.compass.R.layout;
import com.jay.compass.app.StarApplication;
import com.jay.compass.base.RecentItem;
import com.jay.compass.database.RecentDB;
import com.jay.compass.utils.TimeUtil;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class RecentChatAdapter extends BaseAdapter {
	private Context context;
	private LinkedList<RecentItem> recentList = new LinkedList<RecentItem>();
	private RecentDB mRecentDB;
	private StarApplication mApplication;

	public RecentChatAdapter(Context context, ArrayList<RecentItem> list) {
		this.context = context;
		// this.recentList = list;
		mApplication = StarApplication.getInstance();
		mRecentDB = mApplication.getRecentDB();
		recentList = mRecentDB.getRecentList();
		System.out.println("size = " + recentList.size());
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return recentList.size() + 1;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return recentList.get(position - 1);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		// TODO Auto-generated method stub

		recentList = mRecentDB.getRecentList();
		ViewHolder holder = null;
		if (view == null) {
			holder = new ViewHolder();
			view = LayoutInflater.from(context).inflate(R.layout.recent_item,
					parent, false);
			holder.header = (ImageView) view.findViewById(R.id.item_head);
			holder.name = (TextView) view.findViewById(R.id.item_name);
			holder.time = (TextView) view.findViewById(R.id.item_time);
			holder.lastmsg = (TextView) view.findViewById(R.id.item_lastmsg);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		if (position == 0) {
			holder.header.setImageResource(R.drawable.icon_compass);
			holder.name.setText("北斗发送");
			holder.time.setText("");
			holder.lastmsg.setText("点击发送消息");
		} else {
			RecentItem recentItem = recentList.get(position - 1);
			holder.header.setImageResource(recentItem.getHeadImg());
			holder.name.setText(recentItem.getName());
			holder.time.setText(TimeUtil.getChatTime(recentItem.getTime()));
			holder.lastmsg.setText(recentItem.getMessage());
		}
		return view;
	}

	class ViewHolder {
		ImageView header;
		TextView name;
		TextView time;
		TextView lastmsg;
	}
}
